﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using Microsoft.Phone.Tasks;
using CommunityMegaphone.ViewModels;

namespace CommunityMegaphone
{
    public partial class DetailsView : PhoneApplicationPage
    {
        private DateTime _manipStart;
        private bool _scaling = false;
        private int _index = 0;

        public DetailsView()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string selectedIndex = "";
            if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
                _index = int.Parse(selectedIndex);
            if ((object)DataContext == null)
                DataContext = App.SearchResultsViewModel.Events[_index];
        }

        private void OnManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            _manipStart = DateTime.Now;
        }

        private void OnManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            if (!_scaling)
            {
                TimeSpan diff = DateTime.Now - _manipStart;
                if (diff.TotalMilliseconds > 500.0d)
                    _scaling = true;
            }
            if (_scaling)
            {
                ContentText.FontSize *= 1.0d + (e.DeltaManipulation.Translation.X / 500.0d);
                e.Handled = true;
            }
        }

        private void OnManipulationCompleted(object sender, 
            ManipulationCompletedEventArgs e)
        {
            _scaling = false;
        }

        private void OnViewEventMap(object sender, EventArgs e)
        {
            NavigationService.Navigate(
                new Uri("/Views/MapView.xaml?selectedItem="
                    + _index, UriKind.Relative));
        }

        private void OnNavigateToEventWebsite(object sender, EventArgs e)
        {
            var url = ((EventViewModel)DataContext).EventURL;
            if (url == null)
            {
                MessageBox.Show("This event has no website.", 
                    "Sorry", MessageBoxButton.OK);
                return;
            }
            var browser = new WebBrowserTask();
            browser.URL = url;
            browser.Show();
        }
    }
}
